package net.sevencolorlotus.ch01;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @Description: 服务端的业务处理
 * @Author: Jason.zhu
 * @Create: 2020/03/04 14:20
 */
@ChannelHandler.Sharable //添加注解此业务处理类的对象可以处理多个客户端连接
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    /**服务器端读取到网络数据后的处理*/
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception{
        ByteBuf in = (ByteBuf)msg;/*netty实现的缓冲区*/
        System.out.println("Server accept: " + in.toString(CharsetUtil.UTF_8));
        ctx.write(in);
    }

    /**
     * 服务端读取完成网络数据后的处理
     * @param ctx ChannelHandlerContext
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception{
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                .addListener(ChannelFutureListener.CLOSE);
    }
}
